package com.sgg.datastructure.queue;


public class CircleArrayQueue {
    int size;//队列容量
    int[] arr;//数组存放数据
    int front;//队列头指针 指向第一个元素
    int rear;//队列尾指针 指向最后一个元素前一个的位置

    public CircleArrayQueue(int size) {
        this.size = size;
        arr = new int[size];
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列空的,无法取数据");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.printf("a[%d]=%d\n", i % size, arr[i % size]);
        }
    }

    public boolean isFull() {
        return (rear + 1) % size == front;//有一个空位不能加,预留空位
    }

    public boolean isEmpty() {
        return rear == front;
    }


    public void add(int val) {
        if (isFull()) {
            System.out.println("满了,无法添加");
            return;
        }
        arr[rear] = val;
        rear = (rear + 1) % size;
    }

    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列空的,无法取数据");
        }
        int val = arr[front];
        front = (front + 1) % size;
        return val;
    }

    //有效个数
    public int size() {
        return (rear + size - front) % size;
    }

    public int head() {
        if (isEmpty()) {
            throw new RuntimeException("队列空的,无法取数据");
        }
        return arr[front];
    }

    public static void main(String[] args) {
        CircleArrayQueue queue = new CircleArrayQueue(4);
        queue.add(3);
        queue.add(4);
        queue.add(5);
        queue.show();

        System.out.println(queue.get());
        System.out.println(queue.get());
        System.out.println(queue.get());
        queue.add(6);
        System.out.println(queue.head());
        queue.add(7);
        queue.add(8);
        queue.show();
        System.out.println(queue.head());
        System.out.println(queue.get());
        System.out.println(queue.get());
        System.out.println(queue.get());
    }
}
